// var token = '';
var token = localStorage.getItem('token');
var email = '';
$(document).click(function () {
	$('.boxShow.mine').hide();
	$('.server').hide();
})
$('.boxShow.mine').delegate('.logout', 'click', function (e) {
	e.stopPropagation();
	localStorage.removeItem('token');
	window.location.href = "logIn/index.html";
})
$('.clickServer').click(function(e){
	e.stopPropagation();
	if( $('.server').css('display') == 'none' ){
		$('.server').css({'display':'block'});
		$('.mine').css({'display':'none'})
	}else{
		$('.server').css({'display':'none'})
	}
})
var miss,resocket,reajax,ws



// 分页
Vue.component('pager', {
	template: '#page-switch',
	props: ['count', 'current', 'routerName'],
	data: function () {
		return {
			page: 2,
			list: []
		}
	},
	watch: {
		'count': function () {
			this.setList();
		},
		'current': function () {
			this.setList();
		},
		'router-name': function () {
			this.setList();
		}
	},
	updated: function() {
		console.log('updated');
	},
	computed: {
	},
	ready: function () {
		this.page = 1;
		this.setList();
	},
	methods: {
		change: function (page) {
			this.$emit('redirect', page)
		},
		setList: function () {
			this.list = [];
			var count = this.count,
					current = parseInt(this.current);
			var list = [];
			var i = 1;
			for (;i <= count; i++) {
				if (i <= 3 || Math.abs(current - i) <= 1 || count - i < 2 ) {
					list.push(i);
				} else {
					list.push(0);
				}
			}
			for (var j = list.length - 1; j >= 0; j--) {
				if (j > 0 && list[j - 1] == 0 && list[j] == 0) {
					list.splice(j, 1);
				}
			}
			this.list = list;
		}
	}
});
// 分享
Vue.component('share', {
	template: '#share',
	props: ['audio', 'title', 'time', 'size', 'oid', 'qr', 'share'],
	data: function () {
		return {
            // show: true
            playBool: false,
            rewordArr: [8.8, 6.6, 2.2, 1.1],
            reward: 0,
            customRewardShow: false,
            stage: 1,
            qrImg: '',
            api: {
                // apiQR: 'http://testmedia.heardtech.com/Post/PayReward',
                // apiPayStatus: 'http://testmedia.heardtech.com/Post/ajaxRewardIspay'
                apiQR: apiCollect.apiReward,
                apiPayStatus: apiCollect.apiRewardStatus
            },
            intervalId: 0,
            payType: 1,
            payText:'微信'
        }
	},
	computed: {
		qrUrl: function () {
			return 'share.html?orderid=' + this.oid;
		}
	},
	created: function () {
		console.log(this.audio, this.title, this.share)
		// console.log(this.shareLink);
	},
	ready: function () {
		var _this = this;
		if (this.audio) {
			$('#share-audio').on('ended', function () {
				_this.playBool = false;
			})
		}
		var btn = document.getElementById('copyClip');
		var clipboard = new Clipboard(btn);//实例化

		//复制成功执行的回调，可选
		clipboard.on('success', function (e) {
			// console.log(e);
			headtipObj2.show('复制成功');
		});

		//复制失败执行的回调，可选
		clipboard.on('error', function (e) {
			headtipObj.show('您的浏览器不支持该功能');
		});
	},
	methods: {
		close: function () {
			clearInterval(this.intervalId);
			this.$emit('close');
		},
		customRewardSet: function (ev) {
			ev.preventDefault();
			this.customRewardShow = !this.customRewardShow;
		},
        tabWxPay: function(){
            var $this = $('#sharePayType div:first-child');
            $this.addClass('mask_bor_bg').siblings().removeClass('mask_bor_bg');
            this.payType= 1
			this.payText = '微信';
            console.log('当前支付状态'+this.payType);
            // $('.checkbox-simulator').prop('checked',false)
        },
        tabAliPay: function(){
            var $this = $('#sharePayType div:last-child');
            $this.addClass('mask_bor_bg').siblings().removeClass('mask_bor_bg');
            this.payType= 2;
            this.payText = '支付宝';
            console.log('当前支付状态'+this.payType);
            // $('.checkbox-simulator').prop('checked',false)
        },
		audioPlay: function () {
			if (this.playBool) {
				this.playBool = false;
				$('#share-audio').get(0).pause();
			} else {
				this.playBool = true;
				$('#share-audio').get(0).play();
			}
		},
		gotoPage2: function (val) {
			this.reward = val;
			this.stage = 2;
		},
		getQR: function (val) {
			var _this = this;
			// 获取qr
			$.post(_this.api.apiQR, {
				// 数据
				token: localStorage.getItem('token'),
				oid: _this.oid,
				money: val,
				paytype:_this.payType
			}, function (data) {
				if (data.code == '000000') {
					_this.stage = 3;
					// 修改二维码
					_this.qrImg = data.data.fileName;
					_this.getPaymentStatusLoop(data.data.out_trade_no);
				} else {
					headtipObj.show(data.message);
				}
			})
		},
		getPaymentStatusLoop: function (num) {
			var _this = this;
			var cont = true;
			_this.intervalId = setInterval(function () {
				if (cont) {
					cont = false;
					// 询问
					$.post(_this.api.apiPayStatus, {
						token: localStorage.getItem('token'),
						oid: _this.oid,
						out_trade_no: num
					}, function (data) {
						if (data.code == '000000') {
							if (data.data.is_pay == 1) {
								// 成功
								// 正常操作
								_this.stage = 4
								// headtipObj.show(data.message);
								clearInterval(_this.intervalId);
							} else {
								// 失败
								cont = true;
							}
						} else {
							headtipObj.show(data.message);
						}
					})
				}
			}, 1000);
		}
	}
})

var globalStage = 1
var globalIsChose = 0
var globaloid = ''
var resttime = 0
var socket
// 4.19
// 付款组件
Vue.component('payment', {
	template: '#payment',
	props: ['email', 'oid', 'token', 'price', 'balance'],
	data: function () {
		return {
			qrImg: '',
			apiGetQR: apiCollect.apiGetWXQR,
			apiPayStatus: apiCollect.apiGetPayStatus,
			// 测试stage 默认1
			stage: globalStage,
			emailEditing: false,
			eml: '',
			title: '支付订单',
			balanceCheckbox: false,
			regEmail: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
			payType:1,
			logo:'img/public/pay_13.png',
			//随机步长
			step: 0,
			// 随机数默认值
			anchor_num: 0,
			// 主播信息
			anchor_list: {},
			// 倒计时结束标识
			num_cunout: 0,
			// 主播排序方式
			anchor_type: 0,
			// 当前有无主播
			checked: false,
			// 主播id
			uuid: '',
			test: '',
			// 自选单筛选字段
			ischose: globalIsChose,
			selectInfo: {},
        }
	},
	computed: {
		discount: function () {
			return (parseFloat(this.price) * .35).toFixed(2);
		}
	},
	ready: function () {
		// console.log(this.email, this.oid, this.token)
		this.eml = this.email;
		this.anchorList()
	},
	methods: {
		clickVIP: function () {
			headtipObj2.show('该功能仅对高级版/企业版充值用户开放');
		},
        tabAliPay: function(){
            var $this = $('.alipay')
			$this.addClass('mask_bor_bg').siblings().removeClass('mask_bor_bg');
            this.payType= 2
            console.log('当前支付状态'+this.payType)
			this.logo='img/public/pay_14.png'
            $('.noclick').attr("checked",false);
            this.balanceCheckbox = false;
        },
        tabWxPay: function(){
			var $this = $('.mask_footer_pay').eq(0)
            $this.addClass('mask_bor_bg').siblings().removeClass('mask_bor_bg');
            this.payType= 1
			console.log('当前支付状态'+this.payType)
            this.logo='img/public/pay_13.png'
            $('.noclick').attr("checked",false);
            this.balanceCheckbox = false;
        },
		paymentClose: function () {
			this.$emit('close');
			clearTimeout(miss)
		},
		useBalance: function () {
			if ($('.noclick').attr('id') <= 0){
				headtipObj2.show('您的余额不足 请前往充值套餐');
				$('.noclick').attr("checked",false);
				this.balanceCheckbox = false;
			}
			if (this.balanceCheckbox) {
				// 使用余额
				$('.mask_footer_pay').removeClass('mask_bor_bg')
                this.balanceCheckbox = true;
                $('.noclick').attr("checked",true);
            } else {
				// 不使用余额
                this.balanceCheckbox = false;
                $('.noclick').attr("checked",false);
            }
		},
		showQR: function () {
			ajaxLock = false;
			var _this = this;
			if (!_this.regEmail.test(_this.eml)) {
				headtipObj.show('邮箱格式不正确');
			} else {
                if (ajaxLock) return; // 如果有锁 则不进行操作
                ajaxLock = true;			// 如果无锁 先锁定
				$.post(_this.apiGetQR, {
					token: _this.token,
					oid: _this.oid,
					email: _this.eml,
					paytype: _this.payType, // 1 微信 2 支付宝
					isbalance: $('.mask_footer_b input[type="checkbox"]').prop('checked') ? 1 : 0
				}, function (data) {
					if (data.code == '000000') {
                        if (data.data.paystate == 0) {
							_this.qrImg = data.data.fileName;
							_this.stage = 2;
							_this.title = '支付订单(￥' + data.data.paymoney + ')'

							// _this.title = '支付订单'
							_this.getPaymentStatusLoop();
						} else if (data.data.paystate == 1) {
							// 直接跳到支付成功页
							// _this.title = '支付订单(￥' + _this.price + ')'
							// 余额付款
							_this.title = '支付订单'
							if(_this.ischose == 1){
								_this.stage = 4
							}else{
								_this.stage = 3;
							}

						}
                        ajaxLock = false;
					} else {
						headtipObj.show(data.message);
                        ajaxLock = false;
                    }
				})
			}
		},
		payback: function(){
			var _this = this
			_this.stage = 1;
		},
		getPaymentStatusLoop: function () {
			var _this = this;
			var cont = true;
			var id = setInterval(function () {
				if (cont) {
					cont = false;
					// 询问
					$.post(_this.apiPayStatus, {
						token: _this.token,
						oid: _this.oid
					}, function (data) {
						if (data.code == '000000') {
							if (data.data.is_pay == 1) {
								// 成功
								// 正常操作
								_this.title = '支付订单'
								 console.log(_this.ischose)
								if(_this.ischose == 1){
									_this.stage = 4;
								}else{
									_this.stage = 3;
								}


                                clearInterval(id);
							} else {
								// 失败
								cont = true;
							}
						} else {
							Dialog.error(data.messge);
						}
					})
				}
			}, 1000);
		},
		// 随机通知主播个数
		anchorNum: function(){
			var _this = this
		    if ("WebSocket" in window) {
		    	// 测试
		        // ws = new WebSocket("ws://47.95.237.155:2345");
           		ws = new WebSocket("ws://59.110.232.52:2345");
		        ws.onopen = function() {
		            ws.send(globaloid)
		        }
		        ws.onmessage = function (evt) {

		            //不parse你啥也看不明白
		            var data = JSON.parse(evt.data).data.data
		            // delete data.uid
	            	var state = JSON.parse(evt.data).data.state
	            	if(state == 201){
	            	 	_this.stage = 5
					$('.mask_pay_three .mask_finish').find('img').css({
                        'margin': '55px 134px 24px 124px',
                        'width': '130px'
                    });

	            	}else if(state == 202){
	            	 	_this.stage = 3
						_this.num_cunout = 1
						// 优选
						_this.selectInfo = JSON.parse(evt.data).data
	            	}else{
						if(data.length == 1){
							miss = setTimeout(function(){
	                           countDown(360,'process-bar');
	                            $('#process-bar').show()
	                        },120000)
						}
	            	 	if(localStorage.getItem('sound')){
	            	 		_this.anchor_list  = data
							if(data.length>3){
								 $('.anchors-list-content').css({
		                            'overflow': 'scroll',
		                            'overflow-x': 'hidden'
		                        })
							}
			            }else{
			            	_this.anchor_list  = data
							if(data.length>3){
								 $('.anchors-list-content').css({
		                            'overflow': 'scroll',
		                            'overflow-x': 'hidden'
		                        })
							}
			            }
			            _this.num_cunout = 1
	            	}
		         }

		        _this.resocket()
		        _this.reajax()
		    }
			 // 倒计时显示
			setInterval(function() {
				_this.addCount++
				_this.step = Math.floor(Math.random()*2 + 1)
                _this.anchor_num += _this.step
			},3000)
			if(_this.anchor_num >= 125){
                   $.ajax({
                        url: apiCollect.apiPostChoseOrder,
                        type: 'post',
                        dataType: 'json',
                        data: {
                            token: localStorage.getItem('token'),
                            oid: _this.oid,
                        },
                        success: function(data){
                            if(data.code = '000000'){
                                $('.no-one-accept').show().siblings().hide()
                                $('.order_head').eq(4).removeClass('col585858').addClass('colacacac');
                                $('.list-play-btn').empty()
                                _this.anchor_num == 0
                            }
                        },
                        error: function(data){
                            console.log(data)
                        }

                    })
            }
		},
		resocket: function(){
	        resocket = setInterval(function(){
	        	// ws = new WebSocket("ws://47.95.237.155:2345");
           		ws = new WebSocket("ws://59.110.232.52:2345");
	            ws.onopen = function() {
		            ws.send(globaloid)
		        }
		        ws.onmessage = function (evt) {

		            //不parse你啥也看不明白
		            var data = JSON.parse(evt.data).data.data
		            // delete data.uid
	            	var state = JSON.parse(evt.data).data.state
	            	if(state == 201){
	            	 	_this.stage = 5
					$('.mask_pay_three .mask_finish').find('img').css({
                        'margin': '55px 134px 24px 124px',
                        'width': '130px'
                    });

	            	}else if(state == 202){
	            	 	_this.stage = 3
						_this.num_cunout = 1
						// 优选
						_this.selectInfo = JSON.parse(evt.data).data
	            	}else{
	            		// _this.anchor_list  = data
						if(data.length == 1){
							miss = setTimeout(function(){
	                           countDown(360,'process-bar');
	                            $('#process-bar').show()
	                        },120000)
						}
	            	 	if(localStorage.getItem('sound')){
	            	 		_this.anchor_list  = data
							if(data.length>3){
								 $('.anchors-list-content').css({
		                            'overflow': 'scroll',
		                            'overflow-x': 'hidden'
		                        })
							}
			            }else{
			            	_this.anchor_list  = data
							if(data.length>3){
								 $('.anchors-list-content').css({
		                            'overflow': 'scroll',
		                            'overflow-x': 'hidden'
		                        })
							}
			            }
			            _this.num_cunout = 1
	            	}
		         }
	        },20000)
	    },
	    reajax: function(){
	         reajax = setInterval(function(){
	            $.ajax({
	                url: 'http://zb.heardtech.com/Put/Recordinformation ',
	                type: 'post',
	                dataType: 'json',
	                data: {
	                    uuid: globaloid
	                },
	                success: function(data){
	                    console.log(data)
	                },
	            })
	        },20000)
	    },
		// 获取主播信息接口
		anchorList: function(type){
			var _this = this
			_this.anchor_type = type
			$.ajax({
				url: apiCollect.apiPostChoseOrder,
				type: 'post',
				dataType: 'json',
				data: {
					type: _this.anchor_type,
					token: localStorage.getItem('token'),
					oid: _this.oid
				},
				success: function(data){
					if(data.code == '000000'){
						if(data.data.state == 1){
							// 等待主播
							_this.num_cunout = 0
							_this.anchorNum()
						}else if(data.data.state == 2){
							// 选择主播
							_this.num_cunout = 1
							_this.anchor_list = data.data.list
							_this.uuid = ''
							console.log(data.data.list.length)
							if(data.data.list.length>3){
								 $('.anchors-list-content').css({
		                            'overflow': 'scroll',
		                            'overflow-x': 'hidden'
		                        })
							}
							if(data.data.resttime > 60 ){
								var missTime = data.data.resttime - 60
								miss = setTimeout(function(){
		                           countDown(362,'process-bar');
		                            $('#process-bar').show()
		                        },missTime * 1000)
							}else if(data.data.resttime == 60){
								countDown(362,'process-bar');
		                        $('#process-bar').show()
							}else{
								countDown(data.data.resttime * 6,'process-bar');
		                        $('#process-bar').show()
							}
							// resttime = data.data.resttime * 2
							// $('#process-bar').show()
							// countDown(resttime,'process-bar')


							if ("WebSocket" in window) {
						      // 测试
						      // var ws = new WebSocket("ws://47.95.237.155:2345");
            				  ws = new WebSocket("ws://59.110.232.52:2345");
						       ws.onopen = function() {
						            ws.send(globaloid)
						        };
						        ws.onmessage = function (evt) {

						            //不parse你啥也看不明白
						            var data = JSON.parse(evt.data).data.data
						            var state = JSON.parse(evt.data).data.state
						            console.log(state)
						            // 处理数据
						            // delete data.uid
					            	if(state == 201){
					            		_this.stage = 5
					            	}else if(state == 202){
					            		_this.stage = 3
					            		_this.num_cunout = 1
					            		_this.selectInfo = JSON.parse(evt.data).data
					            	}else{
							            if(localStorage.getItem('sound')){
							            	setTimeout(function(){
							            		_this.anchor_list  = data
												if(data.length>3){
														 $('.anchors-list-content').css({
								                            'overflow': 'scroll',
								                            'overflow-x': 'hidden'
								                        })
													}
							            	}, 8000)
								            }else{
								            	_this.anchor_list  = data
												if(data.length>3){
													 $('.anchors-list-content').css({
							                            'overflow': 'scroll',
							                            'overflow-x': 'hidden'
							                        })
												}

								            }
						            	}
						         }

						        _this.reajax()
						        _this.resocket()
						    }
						}else if(data.data.state == 3){
							_this.stage = 5
						}else if(data.data.state == 4){
							_this.stage = 3
							_this.num_cunout = 1
						}else{
							// window.location.reload()
						}
					}else {
						console.log('返回信息错误')
					}
				},
				error: function(data){
					console.log(data.code)
				}
			})
	        if(type == 0){
	        	$('.anchors-list-type').find('span').removeClass('list-type-active')
	            $('.anchors-list-type').find('span').eq(0).addClass('list-type-active')
	        }else if(type == 1){
	        	$('.anchors-list-type').find('span').removeClass('list-type-active')
	            $('.anchors-list-type').find('span').eq(1).addClass('list-type-active')
	        }else if(type ==2){
	        	$('.anchors-list-type').find('span').removeClass('list-type-active')
	            $('.anchors-list-type').find('span').eq(2).addClass('list-type-active')
	        }
		},
		// 选择主播
		selectAnchor: function(uuid,e){
			var $el = $(e.target)
			var _this = this
			$('.list-service-radio').find('img').attr('src', './img/optional/unchecked-btn.png');

			console.log($el)
			if(_this.checked == false){
				$el.parents('.anchors-list-detail').find('.list-service-radio').find('img').attr('src', './img/optional/checked-btn.png')
				_this.uuid = uuid
			}else {
				_this.checked = false
			}
		},
		// 播放主播音频
		playSound: function(sound,e){
			var _this = this
       		var el = e.target
       		localStorage.setItem('sound', sound);
       		if( el.children.length == 0 && _this.checked == false){
       			$('.list-play-btn img').empty()
       			$('.list-play-btn img').attr('src', './img/optional/play.png');
       			var div = '<audio id="anchorSound" src="' + localStorage.getItem('sound') + '" style="display:none" autoplay/>';
       			el.innerHTML = div;
       			$('#anchorSound').bind('ended',function () {
               			el.innerHTML = ''
       					$('.list-play-btn img').attr('src', './img/optional/play.png');
            	})
       			el.setAttribute('src','./img/optional/play.gif')

       		}else{
       			el.innerHTML = ''
       			el.setAttribute('src','./img/optional/play.png')
       		}
    	},
		// 选定主播
		confirmAnchor: function(){
			var _this = this
			if(_this.uuid != ''){
				$.ajax({
				url: apiCollect.apiPostSelectChoseUse,
				type: 'post',
				dataType: 'json',
				data: {
					uuid: _this.uuid,
					token: localStorage.getItem('token'),
					oid: _this.oid
				},
				success: function(data){
					if(data.code == '000000'){
						_this.stage = 3
						_this.num_cunout = 0
						_this.anchor_num = 0
						_this.selectInfo = data.data
						console.log(_this.selectInfo)
					}else {
						headtipObj.show(data.message);
					}
				},
				error: function(data){
					console.log(data)

				}
			})
			}

		},
	}
})
// 评价组件
Vue.component('comment', {
	template: "#comment",
	props: ['nickname', 'level', 'ontime', 'ordercount', 'orderovertime', 'releasetime', 'satisfied', 'uuid', 'audio', 'oid'],
	data: function () {
		return {
			// api: 'http://testmedia.heardtech.com//Post/ScoreOrder',
			// apiRefuse: 'http://testmedia.heardtech.com//Post/RejectOrder',
			api: apiCollect.apiOrderCmt,
			apiRefuse: apiCollect.apiOrderReject,
			star: 0,
			hoverStar: 0,
			commentList: {
				1: false,
				2: false,
				3: false,
				4: false,
				5: false,
				6: false,
				7: false,
				8: false,
				9: false,
				10: false,
				11: false,
				12: false
			},
			rejectList: {
				1: false,
				2: false,
				3: false,
				4: false,
				5: false,
				6: false
			},
			audioStatus: false,
			confirmBtnBool: false,
			rejecting: false,
			redoTxt: ''
		}
	},
	ready: function () {

	},
	methods: {
		close: function () {
			this.$emit('close')
		},
		collect: function () {
			// 收藏
			headtipObj.show('该功能仅对高级版/企业版充值用户开放');
		},
		playAudio: function () {
			var bool = !this.audioStatus;
			if (bool) {
				$('#cmt-audio').get(0).play();
			} else {
				$('#cmt-audio').get(0).pause();
			}
			this.audioStatus = bool;
		},
		confirmStar: function (star) {
			if (star == 1) {
				this.commentList[7] = false;
				this.commentList[8] = false;
				this.commentList[9] = false;
				this.commentList[10] = false;
				this.commentList[11] = false;
				this.commentList[12] = false;
			} else if (star >= 2) {
				this.commentList[1] = false;
				this.commentList[2] = false;
				this.commentList[3] = false;
				this.commentList[4] = false;
				this.commentList[5] = false;
				this.commentList[6] = false;
			}
			this.rejecting = false;
			this.star = star;
			this.activeSubmitBtn();
		},
		starHover: function (data) {
			this.hoverStar = data;
		},
		addReject: function (index) {
			this.rejectList[index] = !this.rejectList[index];
			this.activeSubmitBtn();
		},
		addCmt: function (index) {
			this.commentList[index] = !this.commentList[index];
			this.activeSubmitBtn();
		},
		getCmtList: function () {
			var list = [];
			for (var i = 1; i <= 12; i++) {
				if (this.commentList[i]) {
					list.push(i);
				}
			}
			return list;
		},
		getRejectList: function () {
			var list = [];
			for (var i = 1; i <= 12; i++) {
				if (this.rejectList[i]) {
					list.push(i);
				}
			}
			return list;
		},
		activeSubmitBtn: function () {
			if (this.rejecting) {
				var list = this.getRejectList();
				if (list.length > 0 || this.redoTxt.length > 0) {
					this.confirmBtnBool = true;
				} else {
					this.confirmBtnBool = false;
				}
			} else {
				var list = this.getCmtList();
				if (this.star && list.length > 0) {
					this.confirmBtnBool = true;
				} else {
					this.confirmBtnBool = false;
				}
			}
		},
		pushCmt: function () {
			var _this = this;
			if (_this.rejecting) {
				// 重新配音
				_this.redo();
			} else {
				// 正常配音
				var list = this.getCmtList();
				if (_this.star == 0) {
					headtipObj.show('请选择星级');
				} else if (list.length == 0) {
					headtipObj.show('请选择评论');
				} else {
                    $.ajax({
                        type: 'post',
                        url: this.api,
                        data: {
							token: localStorage.getItem('token'),
							oid: _this.oid,
							score: _this.star,
							passmessage: list
						},
                        beforeSend: function () {
                            $('#bohui').prop('disabled',true);
                        },
                        success: function (data) {
                            if (data.code == '000000') {
								// window.location.reload();
								_this.$emit('refresh');
								_this.$emit('close');
								headtipObj2.show("评价成功 欢迎分享音频/打赏主播");
							}
                            $('#bohui').prop('disabled',false);
                        },
						error:function (data) {
                            headtipObj.show(data.message);
                        }
                    });
				}
			}
		},
		refuse: function () {
			headtipObj2.show('即将开放，敬请期待');
		},
		showReject: function () {
			this.rejecting = true;
			this.activeSubmitBtn();
		},
		redo: function () {
			// 要求重新配音
			var _this = this;
			if (_this.redoTxt.length == 0) {
				headtipObj.show('请输入理由');
			} else {
                $.ajax({
                    type: "POST",
                    url: _this.apiRefuse,
                    data: {
                    	token: localStorage.getItem('token'),
                        oid: _this.oid,
                        passmessage: _this.redoTxt
					},
					beforeSend:function () {
                        $('#bohui').prop('disabled',true);
                    },
                    success: function(data){
                        if (data.code == '000000') {
                            _this.$emit('refresh');
                            _this.$emit('close');
                        }
                    },
					complete:function () {
                        $('#bohui').prop('disabled',false);

                    },
					error:function (data) {
                        headtipObj.show(data.message);
                    }
                });

			}
		}
	}
});

// 详情组件
Vue.component('detail', {
	template: '#detail',
	props: ['type', 'email', 'cmt', 'total', 'price', 'paystatus', 'state', 'quality', 'cmt2', 'achor', 'words','ischose','nickname','isautochose', 'refundtype'],
	data: function () {
		return {
            showWord:true
		}
	},
    created: function(){

	},
	ready: function () {

	},
	methods: {
		close: function () {
			this.$emit('close');
		}
	}
});

var all = Vue.extend({
	template: '#all',
	data: function () {
		return {
			all: {
				toke: token,
				page: '1',
				type: '0',
				email: ''
			},
			list: [],
			mation: {
				level: '',
				uuid: '',
				nickname: '',
				satisfied: '',
				ordercount: '',
				ontime: '',
				orderovertime: '',
				releasetime: ''
			},
			share: {
				show: false,
				audio: '',
				time: '',
				title: '',
				size: '',
				oid: '',
				qr: '',
				shareLink: ''
			},
			payment: {
				show: false,
				email: '',
				oid: '',
				price: 0,
				balance: 0
			},
			page: {
				current: 0, // 目前页数
				count: 0,	  // 总页数
				routerName: 'all', //router name
				page: 0,
				list: []
			},
			comment: {
				show: false,
				star: 0,
				nickname: '',
				level: 0,
				ontime: 0,
				ordercount: 0,
				orderovertime: 0,
				releasetime: '',
				satisfied: 0,
				audio: '',
				uuid: '',
				oid: ''
			},
			// 详情
			detail: {
				show: false,
				type: '极速配音 >优质主播 238字',
				email: '123@qq.com',
				cmt: '-',
				total: '2132',
				price: '23',
				paystatus: 0,
				state: 0,
				quality: '5',
				cmt2: 'dfsdfsdfdsfdsfsd',
				achor: '',
				words: 0,
				ischose: 0,
				nickname: '',
				isautochose:'',
				refundtype: ''
			},
			empty: false
		}
	},
	ready: function () {
		this.setPage();
		this.setTypeFromRoute();
		this.ajaxhtml();
		var _this = this;
		// 获取用户数据
		// 设置改变主体项
		pressSelect.init();
		// 设置个人信息项
		personInfo.init(function () {}, function (data) {
			_this.all.email = data.data.email;

		});


	},
	watch: {
		'$route': function (to, from) {
			// 对路由变化作出响应...
			this.setTypeFromRoute();
			this.clearData();
			this.setPage();
			this.ajaxhtml();
		},
		list(){
			var url = []
			var i =0
			var arr =[]
			var j = new Number()
			var h 
			
			for( i in this.list){
				if( this.list[i].mp3link != '' && (this.list[i].state == 3 ||  this.list[i].state == 4)){
					url[i] = this.list[i].mp3link
					this.getAudio(url[i],i)
					arr.push(i)
					for( j in arr ){
						if( arr[j]-arr[j-1] == 2){
							// 两个音频中间 间隔1个
							
							
							// return false
						}if( arr[j]-arr[j-1] == 3){
							// 两个音频中间 间隔2个c
							console.log(i)
							$(".wx-audio-content[id=" + i + "]").css({
								'margin': '238px auto 0 auto'
							})
						}else if( arr[j]-arr[j-1] == 4){
							// 两个音频中间 间隔3个
							$(".wx-audio-content[id=" + i + "]").css({
								'margin': '324px auto 0 auto'
							})
						}
					}
				}else{
					pre = i - 1
					$(".wx-audio-content[id=" + pre + "]").css({
							'margin-bottom': '145px'
					})
				}
				
			}
			
			
		}

	},
	methods: {
		getAudio: function(url,id){

			var wxAudio = new Wxaudio({
				ele: '.textaudio',
				src: url,
				width: '200px',
				id: id,
				loop: false
			});
			function play() {
				wxAudio.audioPlay()
			}
		},
		goto: function(page) {
			var name = this.$route.name;
			this.$router.go({
				name: name,
				query: {
					page: page
				}
			})
		},
		clearData: function () {
			this.list = [];
		},
		setPage: function () {
			this.page.current = this.$route.query.page ? this.$route.query.page : 1;
			this.page.routerName = this.$route.name;
		},
		showDetail: function (demand, level, words, email, cmt, total, price, state, score, cmt2, paystatus,ischose,nickname,isautochose,refundtype) {
			var orderType = ['签约配音','极速配音', '极速配音', '预约配音'];
			var achorLevel = [0, 0, 0, 0, '顶级主播', '知名主播', '优质主播']
			this.detail.type = orderType[demand];
			this.detail.achor = achorLevel[level - 1];
			this.detail.words = words;
			this.detail.paystatus = paystatus;
			// console.log(paystatus)
			this.detail.email = email;
			this.detail.cmt = cmt;
			this.detail.total = total;
			this.detail.price = price;
			this.detail.ischose = ischose;
			this.detail.nickname = nickname;
			this.detail.state = state
			this.detail.isautochose = isautochose
			this.detail.refundtype = refundtype
			console.log(refundtype)


			var status = ['未接单', '已接单', '已交付未结算', '已交付已结算', '需要重新上传音频'];
			// if (state == 1) {
			// 	this.detail.state = '-'
			// } else if (ischose != 1 &&state == 2 || state == 5) {
			// 	this.detail.state = '配音中'
			// } else if (ischose != 1 && state == 3 || state == 4) {
			// 	this.detail.state = '已交付'
			// }else if(ischose == 1 && state == 6){
			// 	this.detail.state = '订单关闭'
			// }else if(ischose == 1 && state == 7){
			// 	this.detail.state = nickname
			// }
			this.detail.quality = score;
			this.detail.cmt2 = cmt2;
			this.detail.show = true;
		},
		cancelOrder: function (id) {
			var _this = this;
			commonConfirmBox.show({
				title: '取消订单',
				text: '是否取消该订单？'
			}, function () { }, function () {
				// 确认后重置
				$.post(apiCollect.apiDeleteOrder, {
					token: localStorage.getItem('token'),
					oid: id
				}, function (data) {
					if (data.code == '000000') {
						// 删除成功
						_this.ajaxhtml();
						commonConfirmBox.hide();
					} else {
						headtipObj.show(data.message);
					}
				})
			})
		},
		delete: function (id) {
			var _this = this;
			commonConfirmBox.show({
				title: '删除订单',
				text: '是否删除该订单？'
			}, function () { }, function () {
				// 确认后重置
				$.post(apiCollect.apiDeleteOrder, {
					token: localStorage.getItem('token'),
					oid: id
				}, function (data) {
					if (data.code == '000000') {
						// 删除成功
						_this.ajaxhtml();
						commonConfirmBox.hide();
					} else {
						headtipObj.show(data.message);
					}
				})
			})
		},
		setTypeFromRoute: function () {
			var typeObj = {
				'all': 0,
				'wait': 1,
				'dong': 2,
				'finish': 3,
				'talk': 4
			};
			this.all.type = typeObj[this.$route.name];
		},
		paymentShow: function (oid, email, price,ischose,isPay) {
			var _this = this
			globaloid = oid
			$('.textaudio').css('z-index','0')
			if(ischose == 1){
				// 自选单未付款
				if(isPay == 0){
					globalStage = 1
				}else {
					globalStage = 4
				}
				globalIsChose = 1
			}else {
				// 普通单未付款
				globalStage = 1
				globalIsChose = 0

			}
			$.post(apiCollect.apiGetBalance, {
				wid: localStorage.getItem('wid')
			}, function (data) {
				if (data.code == '000000') {
					// 付款组件显示
					_this.payment.show = true;
					_this.payment.oid = oid;
					_this.payment.price = price;
					_this.payment.email = email;
					_this.payment.balance = data.data.balance;
					_this.payment.actualnumber= data.payment
					// console.log(_this.payment.actualnumber)
				} else {
					headtipObj.show(data.message);
				}
			})
		},
		// 再次下单
		reOrder: function(oid){
			var _this = this
			$.ajax({
				url: apiCollect.apiPostReOrder,
				type: 'post',
				dataType: 'json',
				data: {
					token: localStorage.getItem('token'),
					oid: oid
				},
				success: function(data){
					// console.log(data.data)
					window.location.href='speeDdubbing.html'

				},
				error: function(data){
					console.log(data.data)
				}
			})
		},
		paymentClose: function () {
			// 付款组件关闭
			window.location.reload()
			this.payment.show = false;

		},
		shareShow: function (show, audio, time, title, size, id, qr, shareLink) {
			// 分享组件显示或者关闭
			this.share.show = show;
			this.share.audio = audio;
			this.share.oid = id;
			this.share.qr = qr;
			this.share.shareLink = shareLink;
			if (time) {
				var minutes = Math.floor(time / 60);
				var seconds = time % 60;
				this.share.time = (minutes > 10 ? minutes : '0' + minutes) + ':' + (seconds > 10 ? seconds : '0' + seconds);
			} else {
				this.share.time = 0;
			}
			this.share.title = title;
			this.share.size = size;
		},
		ajaxhtml: function () {
			var _self = this;
			$.ajax({
				type: "POST",
				url: apiCollect.apiOrderList,
				data: {
					token: _self.all.toke,
					page: _self.page.current,
					type: _self.all.type
				},
				success: function (data) {
					if (data.code == '000000') {
						_self.all.page += 1;
						_self.list = data.data.order ? data.data.order : [];
						_self.page.count = data.data.count;
						if (_self.list.length == 0) {
							_self.empty = true;
						} else {
							_self.empty = false;
						}
					} else {
						console.log(data.message)
					}
				}
			});
		},
		talke: function (item, audio) {
			var _self = this;
			$.ajax({
				type: "POST",
				url: apiCollect.apiOrderCmtInfo,
				data: {
					token: _self.all.toke,
					oid: item
				},
				success: function (data) {
					if (data.code == '000000') {
						// 显示评价窗口
						_self.comment.nickname = data.data.nickname;
						_self.comment.satisfied = data.data.satisfied;
						_self.comment.ordercount = data.data.ordercount;
						_self.comment.ontime = data.data.ontime;
						_self.comment.releasetime = data.data.releasetime;
						_self.comment.orderovertime = data.data.orderovertime;
						_self.comment.level = data.data.level;
						_self.comment.audio = audio;
						_self.comment.oid = item;
						_self.comment.show = true;
					} else {
						headtipObj.show(data.message);
					}
				}
			});
		},
		share: function () {
			Dialog.customsMessage("<div class='talker-mask-line'></div>" +
				"<div class='mask-s-title'>" +
				"<img src='img/mask-icon.png' class='mask-s-logo fl'>" +
				"<div class='mask-s-mail fl'>" +
				"<p class='px14 col-59'>乐视裁员风暴...</P>" +
				"<p class='px12 col-59 line-19'>08:33</p>" +
				"<p class='px12 col-59 line-19 col-94'>12.5M</p>" +
				"</div>" +
				"<div class='mask-s-r fl mar-15'>" +
				"<img src='img/mask-down.png' class='mask-s-img'>" +
				"<a href='javascript:;' class='mask-s-rt px12 col-94 line-33'>下载</a>" +
				"</div>" +
				"<div class='mask-s-r fl'>" +
				"<img src='img/mask-code.png' class='mask-s-img'>" +
				"<a href='javascript:;' class='mask-s-rt px12 col-94 line-33'>扫码</a>" +
				"</div>" +
				"</div>", "", "", "分享/打赏");
		}
	}
});

Vue.component('mask', {
    template: '#mask',
    props: ['status'],
    data: function () {
        return {
            text: '选择您要配音的文本文件',
            api: 'http://testoss.heardtech.com/demo.php',
            uploaded: false,
            fileName: '',
            docTitle: '',
            weburl: '',
            webBtnActive: false,
            url:''
        }
    },
    ready: function () {
    },
    watch:{
        "weburl":function() { //此处不要使用箭头函数
            if (this.weburl) {
                this.webBtnActive = true;
            } else {
                this.webBtnActive = false;
            }
        }
    },
    methods: {
        analysisUrl: function () {
            var _this = this;
            if (_this.webBtnActive) {
                $.post(apiCollect.apiGetArticleContent, {
                    url: _this.weburl
                }, function(data) {
                    if (data.code == '000000') {
                        window.location.href = 'speeDdubbing.html?file=' + encodeURIComponent(encodeURIComponent(data.data.txt))
                            + '&title=' + encodeURIComponent(encodeURIComponent(data.data.title));
                    } else {
                        headtipObj.show(data.message);
                    }
                })
            }
        },
        activeWebBtn: function () {
            if (this.weburl) {
                this.webBtnActive = true;
            } else {
                this.webBtnActive = false;
            }
        },
        close: function () {
            this.$emit('close');
        },
        switchMask: function (status) {
            console.log('emit change', status);
            this.$emit('switch', status);
        },
        gotoEditor: function () {
            if (this.uploaded) {
                var url = './speeDdubbing.html?file=' + encodeURIComponent(encodeURIComponent(this.fileName)) +
                    "&title=" + encodeURIComponent(encodeURIComponent(this.docTitle));
                window.location.href = url;
            }
        },
        selectFile: function () {
            $('#upload-word').trigger('click');
        },
        upload: function (e) {
            // console.log(this.file)
            var _this = this;
            var file = e.target.files[0];
            // console.log(file)
            var timeStamp = new Date().getTime();
            var storeAs = timeStamp + '.docx';//这个用于请求获取文章内容的
            _this.fileName = storeAs;
            _this.docTitle = file.name.substring(0, file.name.lastIndexOf('.'));
            OSS.urllib.request(_this.api, { method: 'GET' }, function (err, response) {
                _this.text = '上传中';
                if (err) {
                    return alert(err);
                }
                try {
                    result = JSON.parse(response);
                } catch (e) {
                    return alert('parse sts response info error: ' + e.message);
                }
                console.log(result)
                var client = new OSS.Wrapper({
                    accessKeyId: result.Credentials.AccessKeyId,
                    accessKeySecret: result.Credentials.AccessKeySecret,
                    stsToken: result.Credentials.SecurityToken,
                    endpoint: 'oss-cn-beijing.aliyuncs.com',
                    bucket: 'heard-word'
                });
                client.multipartUpload(storeAs, file).then(function (result) {
                    console.log('上传成功:', result);
                    _this.text = file.name;
                    _this.fileName = storeAs;
                    _this.uploaded = true;
                    console.log(_this.docTitle);
                    // $('.mask_wrap .mask_up .mask_c_btn').addClass('btn-black');
                }).catch(function (err) {
                    console.log(err);
                });
            });
        }
    }
});

var Vm = new Vue({
	el: '.leftNav',
	data: {
		name: [{
			'name': '配音服务',
			'src': 'img/little_logo_03.png',
			'url': 'index.html',
			'class': 'voice'
		},
		{
			'name': '我的订单',
			'src': 'img/little_logo_06.png',
			'url': '#',
			'class': 'order'
		},
		{
			'name': '发现主播',
			'src': 'img/little_logo_08.png',
			'url': '#',
			'class': 'search'
		},
		{
			'name': '设置偏好',
			'src': 'img/little_logo_10.png',
			'url': 'index.html?type=2',
			'class': 'setting'
		}
		],
		names: [{
			'name': '收藏主播',
			'src': 'img/little_logo_12.png',
			'url': '#',
			'class': 'mark'
		},
		{
			'name': '充值套餐',
			'src': 'img/little_logo_14.png',
			'url': '#',
			'class': 'money'
		}
		],
		activeIndex: 1,
		two: '100',
		moreShow: false,
		mask: {
			show: false,
			status: 0
		}
	},
	ready: function () {
		var _this = this;
		$('body').click(function () {
			_this.moreShow = false;
		})
	},
	methods: {
		addclass: function (index) {
			this.two = 100;
			this.off = index;
		},
		adds: function (index) {
			this.off = 100;
			this.two = index;
		},
		showMore: function () {
			this.moreShow = !this.moreShow;
		},
		showMaskURL: function (ev) {
			// 显示输入网页
			this.moreShow = false;
			this.mask.show = true;
			this.mask.status = 1;
		},
		showMaskUpload: function (ev) {
			// 显示上传
			this.moreShow = false;
			this.mask.show = true;
			this.mask.status = 2;
		},
		changeMask: function (val) {
			console.log('status', val);
			this.mask.show = true;
			this.mask.status = val;
		}
	}
});

var router = new VueRouter();
router.map({
    '/all': { component: all, name: 'all' },
    '/wait': { component: all, name: 'wait' },
    '/dong': { component: all, name: 'dong' },
    '/finish': { component: all, name: 'finish' },
    '/talk': { component: all, name: 'talk' }
});
router.redirect({ '/': 'all' });
var App = Vue.extend({});
router.start(App, '#app');

// 实时监听input值
$('.user_img').click(function(e){
    e.stopPropagation();
    if( $('.mine').css('display') == 'none' ){
        $('.mine').css({'display':'block'})
        $('.textaudio').css({'z-index': '0'})
        $('.server').css({'display':'none'})
    }else{
    	$('.textaudio').css({'z-index': '333'})
        $('.mine').css({'display':'none'})
    }
})

// 倒计时
function countDown(time,id){
    var counter = (function () {
        var count = time;
        var time_num = 60

        if((time/6) < 60){
        	time_num = time/6
        }
            return function () {
                time_num --
                if(time_num <= 20){
                    $('.select-anchor-btn').css({'background': "#FF260F",'opacity':'0.59'}).val('倒计时结束后，系统将为你优选主播')
                }
                if(time_num<1){
                    time_num = 0
                    clearInterval(timeCount)
                }
                $('#process-num').text(time_num+'s')
                return count-= 6
            }
    })();
    function begin () {
        $('#'+id).css('width',counter()+'px');
        if ($('#'+id).css('width') == time/6+'px') {

        }
    }
    var timeCount = setInterval(begin,1000);
}
